const express = require('express');
const router = express.Router();
const multer = require('multer');
const fs = require('fs')
const XLSX = require('xlsx')
const path = require('path')
const cheerio = require('cheerio')
const { parseDocument } = require('htmlparser2')
const moment = require('moment');
let fileName = null
let newData = null
let htmlFileName = null
let replaceTimmes = 0
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'public/files/') // 设置上传文件保存的目录
  },
  filename: function (req, file, cb) {
    let name = Date.now() + '-' + file.originalname
    if (file.originalname.includes('html')) {
      htmlFileName = name
    } else {
      fileName = name
    }
    cb(null, name) // 设置文件名，这里用时间戳加原始文件名避免重名
  }
});
const upload = multer({ storage: storage });
// 递归查找
function replaceText(domObject, map) {
  if (domObject.type === 'text' && domObject.parent.name !== 'script') {
    if (domObject.data.trim() !== '') {
      for (let key in map) {
        // 切割字符串并且排空
        const elTextArr = domObject.data.trim().split(' ').filter(i => {
          i=i.replace(/[^a-zA-Z0-9]/g, '');
          return i!==''
        })
        if (elTextArr.length > 0 && !elTextArr[0].startsWith("{%") && !elTextArr.at(-1).endsWith("%}")) {
          const dictKey = key.toUpperCase().trim()
          const textFirst = elTextArr[0].toUpperCase().trim()
          const textLast = elTextArr.at(-1).toUpperCase().trim()
          // 如果是多个单词，首尾对比
          if (dictKey.startsWith(textFirst) && dictKey.endsWith(textLast)) {
            domObject.data = map[key]
            // 判断data-title 属性是否存在
            if (domObject.parent.attribs["data-title"]) {
              domObject.parent.attribs["data-title"] = map[key]
            }
            replaceTimmes++
            break;
          }
        } else {
          // 单个单词相等对比
          if (key === domObject.data) {
            domObject.data = map[key]
            if (domObject.parent.attribs["data-title"]) {
              domObject.parent.attribs["data-title"] = map[key]
            }
            replaceTimmes++
            break;
          }
        }
      }
    }
  }

  if (domObject?.children && Array.isArray(domObject.children) && domObject.children.length > 0) {
    domObject.children.forEach(i => replaceText(i, map))
  }
}

router.post('/', upload.fields([{ name: 'xlsxFile', maxCount: 1 }, { name: 'htmlFile', maxCount: 1 }]), (req, res) => {
  if (!req.files.xlsxFile && !req.files.htmlFile && !req.body.transKey && !req.body.transValue) {
    return res.status(400).send('No file uploaded.');
  }
  // 读取xlsx 生成数据
  const workbook = XLSX.readFile(path.join(process.cwd(), 'public/files/' + fileName));
  const worksheet = workbook.Sheets[workbook.SheetNames[0]];
  const map = {}
  for (let rowKey in worksheet) {
    if (rowKey[0] === '!') continue;
    if (rowKey.includes(req.body.transKey)) {
      const rowNumber = rowKey.match(/\d+/)[0]
      try {
        if (worksheet[req.body.transValue + rowNumber]) {
          map[worksheet[rowKey].v] = worksheet[req.body.transValue + rowNumber].v
        }
      } catch (err) {

        return res.send({
          code: 400,
          msg: '翻译键或翻译值有错误，请检查'
        })
      }
    }
  }

  fs.readFile(path.join(process.cwd(), 'public/files/' + htmlFileName), 'utf8', (err, data) => {
    if (err) {
      console.error('读取文件时发生错误:', err);
      return;
    }
    // 去除br标签
    const jquery = cheerio.load(data);
    jquery('br').replaceWith(' ');

    newData = parseDocument(jquery.html()); 
    replaceText(newData, map)

    const $ = cheerio.load(newData)

    newData = $.html().replace(/&lt;/g, '<').replace(/&gt;/g, '>');
    // console.log(newData);
    fs.writeFile(path.join(process.cwd(), 'public/files/' + `${Date.now()}-new.html`), newData, 'utf-8', () => {
      if (err) {
        console.error(err);
      } else {
        console.log(`自动替换成功，共替换${replaceTimmes}个`);
        const logXlsx = XLSX.readFile(path.join(process.cwd(), 'public/log.xlsx'));
        const logWorksheet = logXlsx.Sheets['Sheet1'];
        const jsonData = XLSX.utils.sheet_to_json(logWorksheet);
        const newData = [
          { times: replaceTimmes, date: moment().format('YYYY-MM-DD HH:mm:ss') },
          ...jsonData
        ];
        const newRows = XLSX.utils.json_to_sheet(newData);
        const excleBook = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(excleBook, newRows, 'Sheet1')
        // 写入文件
        XLSX.writeFile(excleBook, 'public/log.xlsx');
        replaceTimmes = 0
      }
    })
    res.send({
      code: 200,
      msg: "sucess",
      data: newData,
    });
  });
})
module.exports = router